/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ar.com.neolokura.travian.helper.account.admin;

import ar.com.neolokura.travian.helper.account.entity.Account;
import ar.com.neolokura.travian.helper.account.entity.Village;
import ar.com.neolokura.travian.helper.browser.admin.BrowserAdmin;
import ar.com.neolokura.travian.helper.constant.TravianWebTree;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.log4j.Logger;

/**
 *
 * @author gustavo
 */
public class AccountAdmin {
    private static Logger logger = Logger.getLogger(AccountAdmin.class.getSimpleName());
    private static AccountAdmin INSTANCE = null;
    private WebClient webClient;

    // Private constructor suppresses 
    private AccountAdmin() {
        BrowserAdmin browserAdmin = BrowserAdmin.getInstance();
        webClient = browserAdmin.getWebClientInstance();
        logger.info(">> AccountAdmin started...");
    }

    // creador sincronizado para protegerse de posibles problemas  multi-hilo
    // otra prueba para evitar instanciación múltiple 
    private synchronized static void createInstance() {
        if (INSTANCE == null) {
            INSTANCE = new AccountAdmin();
        }
    }

    public static AccountAdmin getInstance() {
        if (INSTANCE == null) {
            createInstance();
        }
        return INSTANCE;
    }
    
    public Account getAccount() throws Exception{
        
        AccountHelper helper = new AccountHelper();
        AccountParser parser = new AccountParser();
        // Goes to the login page
        TravianWebTree tree = new TravianWebTree();
        HtmlPage page = webClient.getPage(tree.getLoginPage());
        
        // Gets the link for each village
        ArrayList<String> villageLinks = parser.getVillageIds(page.asXml());
        
        //HashMap<Link,Village> for the account
        HashMap<String,Village> villages = new HashMap<String, Village>();
        for(String villageId : villageLinks) {
            HtmlPage villagePage = webClient.getPage(tree.getVillageLink(villageId));
            Village village = helper.getVillageByPage(villagePage);
            villages.put(villageId, village);
        }
        
        Account account = new Account();
        account.setVillages(villages);
        
        return account;
    }

  
    
    

}
